package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

public class Utils {
    public static WebDriver driver = null;
    public Utils(String url){
        //创建driver对象
        driver = createDriver();

        //访问指定的url
        driver.get(url);
    }
    public static WebDriver createDriver(){
        if(driver == null){
            //打开浏览器驱动
            WebDriverManager.chromedriver().setup();
            //将驱动的访问权限打开
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            //创建驱动对象
            driver = new ChromeDriver(options);
        }
        //默认设置每个搜索元素的语句隐式等待两秒
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        return driver;
    }

    public static void getSreenShoot(String methodName) throws IOException {
        //设置文件命名格式
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        //生成文件名需要的时间戳
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        //拼接文件路径
        String fileName = ".src/test/image" + dirTime + "/" + methodName + "-" + fileTime + ".png";

        //生成屏幕截图
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

        //将屏幕截图放在指定位置
        FileUtils.copyFile(srcFile, new File(fileName));
    }
}
